package ua.org.plast.mobileApp;


import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.*;
import android.view.animation.AnimationUtils;
import ua.org.plast.mobileApp.fragments.BaseFragment;
import ua.org.plast.mobileApp.fragments.FirstFragment;
import ua.org.plast.mobileApp.fragments.SecondFragment;
import ua.org.plast.mobileApp.literature.BooksFragment;
import ua.org.plast.mobileApp.navigation.NavigationAdapter;
import ua.org.plast.mobileApp.navigation.NavigationDrawerListView;
import ua.org.plast.mobileApp.navigation.NavigationItem;
import ua.org.plast.mobileApp.news.NewsFragment;
import ua.org.plast.mobileApp.songbook.SongbookFragment;


public class MainActivity extends ActionBarActivity {
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;

    private static NavigationItem.SubItem[] newsSubItems = {
            new NavigationItem.SubItem(App.getContext().getResources().getString(R.string.nav_news_portal), NewsFragment.class),
            new NavigationItem.SubItem(App.getContext().getResources().getString(R.string.nav_news_kyiv), SecondFragment.class)
    };

    private static NavigationItem.SubItem[] litSubItems = {
            new NavigationItem.SubItem(App.getContext().getResources().getString(R.string.nav_literarura_pravulnyk), FirstFragment.class),
            new NavigationItem.SubItem(App.getContext().getResources().getString(R.string.nav_literarura_proby), SecondFragment.class),
            new NavigationItem.SubItem(App.getContext().getResources().getString(R.string.nav_literarura_knygy), BooksFragment.class)
    };

    private static NavigationItem[] navigationItems = {
            new NavigationItem(R.drawable.mercury, App.getContext().getResources().getString(R.string.nav_news), NewsFragment.class, newsSubItems),
            new NavigationItem(R.drawable.venus, App.getContext().getResources().getString(R.string.nav_spivanyk), SongbookFragment.class),
            new NavigationItem(R.drawable.earth, App.getContext().getResources().getString(R.string.nav_literarura), FirstFragment.class, litSubItems),
            new NavigationItem(R.drawable.mars, App.getContext().getResources().getString(R.string.nav_practycne_plastuvania), FirstFragment.class),
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        ((FrameLayout) findViewById(R.id.content_frame)).addView();
        findViewById(R.id.content_frame).startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
        mTitle = mDrawerTitle = getTitle();
        ;
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        NavigationDrawerListView unitView = (NavigationDrawerListView) findViewById(R.id.left_drawer);
        unitView.setSwitcher(new NavigationAdapter.Switcher() {

            @Override
            public void switchTo(Class<? extends BaseFragment> fragment) {
                switchToFragment(fragment);
            }
        });
        unitView.setAdapter(new NavigationAdapter(this, navigationItems, new NavigationAdapter.Switcher() {

            @Override
            public void switchTo(Class<? extends BaseFragment> fragment) {
                switchToFragment(fragment);
            }
        }));
//        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
//        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
//                R.layout.drawer_list_item, mPlanetTitles));
//        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed(View view) {
                getSupportActionBar().setTitle(mTitle);
            }

            public void onDrawerOpened(View drawerView) {
                getSupportActionBar().setTitle(mDrawerTitle);
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            switchToFragment(FirstFragment.class);
        }
    }

    private void switchToFragment(Class<? extends BaseFragment> fragment) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if (fm.findFragmentByTag(fragment.getCanonicalName()) != null) {
            ft.commit();
            mDrawerLayout.closeDrawers();
            return;
        }
        try {
            BaseFragment baseFragment = fragment.newInstance();
            setTitle(baseFragment.getActivityLabel());
            fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
            ft.replace(R.id.content_frame, baseFragment, fragment.getCanonicalName());
            mDrawerLayout.closeDrawers();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        ft.commit();
    }

    public void showPopupFragment(Class<? extends BaseFragment> fragment, Bundle arguments) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        BaseFragment baseFragment;
        try {
            baseFragment = fragment.newInstance();
            setTitle(baseFragment.getActivityLabel());
            if (arguments != null) {
                baseFragment.setArguments(arguments);
            }
            ft.add(R.id.content_frame, baseFragment);
            ft.addToBackStack(null);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            ft.commit();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_actions, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
//        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}
